#!/usr/bin/env python3
"""
用户认证路由
"""

from flask import Blueprint, request, jsonify
from flask_jwt_extended import (
    create_access_token, create_refresh_token,
    jwt_required, get_jwt_identity
)
from models import db, User, Role, UserRole
from config import Config

bp = Blueprint('auth', __name__)

@bp.route('/register', methods=['POST'])
def register():
    """用户注册"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        if not data or not data.get('email') or not data.get('password'):
            return jsonify({'error': '邮箱和密码为必填项'}), 400
        
        email = data['email']
        password = data['password']
        username = data.get('username', email.split('@')[0])
        
        # 检查用户是否已存在
        if User.query.filter_by(email=email).first():
            # 兼容测试断言（包含 already exists 文案）
            return jsonify({'error': 'Email already exists'}), 400
        
        if User.query.filter_by(username=username).first():
            return jsonify({'error': '该用户名已被使用'}), 400
        
        # 创建新用户
        user = User(email=email, username=username)
        user.set_password(password)
        
        db.session.add(user)
        db.session.commit()

        # 默认分配 "user" 角色（如果启用了 RBAC 并存在该角色）
        try:
            role = Role.query.filter_by(name='user').first()
            if role:
                user_role = UserRole(user_id=user.id, role_id=role.id)
                db.session.add(user_role)
                db.session.commit()
        except Exception:
            db.session.rollback()
        
        # 创建 token（identity 必须是字符串）
        access_token = create_access_token(identity=str(user.id))
        refresh_token = create_refresh_token(identity=str(user.id))
        
        return jsonify({
            'success': True,
            'message': '注册成功',
            'user': user.to_dict(),
            'access_token': access_token,
            'refresh_token': refresh_token
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


@bp.route('/login', methods=['POST'])
def login():
    """用户登录"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        if not data or not data.get('email') or not data.get('password'):
            return jsonify({'error': '邮箱和密码为必填项'}), 400
        
        email = data['email']
        password = data['password']
        
        print(f"[AUTH] Login attempt: {email}")
        
        # 查找用户
        user = User.query.filter_by(email=email).first()
        
        if not user or not user.check_password(password):
            print(f"[AUTH] Login failed: Invalid credentials for {email}")
            return jsonify({'error': '邮箱或密码错误'}), 401
        
        # 创建 token（identity 必须是字符串）
        access_token = create_access_token(identity=str(user.id))
        refresh_token = create_refresh_token(identity=str(user.id))
        
        print(f"[AUTH] Login successful: {user.email} (ID: {user.id})")
        print(f"[AUTH] Access token generated: {access_token[:50]}...")
        
        return jsonify({
            'success': True,
            'message': '登录成功',
            'user': user.to_dict(),
            'access_token': access_token,
            'refresh_token': refresh_token
        }), 200
        
    except Exception as e:
        print(f"[AUTH ERROR] Login exception: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'error': str(e)}), 500


@bp.route('/refresh', methods=['POST'])
@jwt_required(refresh=True)
def refresh():
    """刷新访问令牌"""
    try:
        current_user_id = get_jwt_identity()
        access_token = create_access_token(identity=current_user_id)
        
        return jsonify({
            'access_token': access_token
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@bp.route('/me', methods=['GET'])
@jwt_required()
def get_current_user():
    """获取当前用户信息"""
    try:
        current_user_id = get_jwt_identity()
        print(f"[AUTH] Getting user info for ID: {current_user_id} (type: {type(current_user_id)})")
        
        # 将字符串 ID 转换为整数
        user = User.query.get(int(current_user_id))
        
        if not user:
            print(f"[AUTH ERROR] User not found: {current_user_id}")
            return jsonify({'error': '用户不存在'}), 404
        
        print(f"[AUTH] User found: {user.email}")
        user_data = user.to_dict()
        # 如果启用 RBAC，返回角色列表
        if getattr(Config, 'FEATURE_RBAC', False):
            try:
                from sqlalchemy import select
                roles = (
                    db.session.query(Role.name)
                    .join(UserRole, Role.id == UserRole.role_id)
                    .filter(UserRole.user_id == user.id)
                    .all()
                )
                user_data['roles'] = [r[0] for r in roles]
            except Exception:
                user_data['roles'] = []
        return jsonify({'user': user_data}), 200
        
    except Exception as e:
        print(f"[AUTH ERROR] Exception in get_current_user: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'error': str(e)}), 500


@bp.route('/logout', methods=['POST'])
@jwt_required()
def logout():
    """用户登出（客户端需要删除 token）"""
    return jsonify({
        'success': True,
        'message': '登出成功'
    }), 200

